<template>
  <div style="display: flex">
    <category-panel
      title="分类"
      icon="tree"
      request="companyCategory"
      @delClick="delClick"
      @notClick="notClick"
      @nodeClick="nodeClick"
    ></category-panel>
    <el-container>
      <el-header>
        <div class="report_header" ref="headerHeight">
          <div class="report_header_left"></div>
          <div style="width: 300px;display: flex;align-items: center;margin-left: 10px;">
            <svg-icon class="primary" :icon-class="$route.meta.icon"/>
            <span style="margin-left: 5px;" class="primary">{{$route.meta.title}}</span>
          </div>
          <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">
            <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px">

              <div class="report_header_query">
                <el-input prefix-icon="el-icon-search" placeholder="企业名称"  v-model="query.name"></el-input>
              </div>
              <div class="report_header_query">
                <el-input prefix-icon="el-icon-search" placeholder="企业编号" v-model="query.code"></el-input>
              </div>
            </div>
            <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="queryClick">查询</el-button>
            <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="addClick"
                       v-permission="['companyList.add']">新增</el-button>
          </div>
        </div>

      </el-header>
      <div class="pd10">

        <el-table
          :data="memberData"
          border
          stripe
          :height="curHeight"
          v-loadMore="[payLoads,'company-list-table']"
          ref="table"
          style="width: 100%;"
        >
          <el-table-column label="企业名称" prop="name"></el-table-column>
          <el-table-column label="企业编号" prop="code"></el-table-column>
          <el-table-column label="手机号码" align="center" prop="mobile" width="110"></el-table-column>
          <el-table-column label="企业分类" align="center" prop="companyCategoryName" width="120"></el-table-column>
          <!-- <el-table-column label="最近充值金额" align="center" prop="rechangeAmount" width="130"></el-table-column> -->
          <!-- <el-table-column label="最近充值时间" align="center" prop="rechangeDate" width="130"></el-table-column> -->
          <el-table-column label="地址" prop="address"></el-table-column>
          <el-table-column label="创建日期" prop="createDate" align="center" width="100"></el-table-column>
          <!-- <el-table-column label="最近修改时间" prop="modifyDate" align="center" width="160"></el-table-column> -->
          <el-table-column label="功能" fixed="right" width="80" align="center">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                content="查看详情"
                placement="top-start"
                v-show="deleted == false"
                v-permission="['companyList.query']"
              >
                <el-button
                  @click="detailClick(scope.row)"
                  type="primary"
                  size="mini"
                >详情</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="80">
            <template slot-scope="scope">
              <div>
                <el-tooltip
                  v-permission="['companyList.edit']"
                  class="item"
                  effect="dark"
                  content="修改企业信息"
                  v-show="deleted == false"
                  placement="top-start"
                >
                  <a @click="editClick(scope.row)">
                    <i style="color: #409EFF" class="el-icon-edit"></i>
                  </a>
                </el-tooltip>
                <el-tooltip
                  v-permission="['companyList.query']"
                  class="item"
                  effect="dark"
                  content="查看详情"
                  v-show="deleted == true"
                  placement="top-start"
                >
                  <a style="margin-left: 10px" @click="detailClick(scope.row)">
                    <i style="color: #409EFF" class="el-icon-document"></i>
                  </a>
                </el-tooltip>
                <el-tooltip
                  class="item"
                  v-permission="['companyList.del']"
                  effect="dark"
                  content="恢复企业"
                  v-show="deleted == true"
                  placement="top-start"
                >
                  <a style="margin-left: 10px" @click="restoreMchCourse(scope.row)">
                    <i style="color: #E6A23C" class="el-icon-refresh-right"></i>
                  </a>
                </el-tooltip>
                <el-tooltip
                  v-permission="['companyList.del']"
                  class="item"
                  effect="dark"
                  content="删除企业"
                  v-show="deleted == false"
                  placement="top-start"
                >
                  <a style="margin-left: 10px" @click="deleteMember(scope.row)">
                    <i style="color: #F56C6C" class="el-icon-delete"></i>
                  </a>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-footer class="el-footerBox">
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="pageNum"
          :limit.sync="pageSize"
          @pagination="loadMember"
        ></pagination>
      </el-footer>
    </el-container>
  </div>
</template>

<style scoped>
</style>

<script>
import permission from "@/directive/permission/index.js"; // 权限判断指令
import { list, del, update, restoreCompany } from "@/api/company";
import utils from "../../utils/utils.js";
import { EventBus } from "@/api/eventBus";
import Pagination from "@/components/Pagination";
import CategoryPanel from "@/components/CategoryPanel";
import ExportList2Excel from "@/components/ExportList2Excel";
import loadMore from "@/utils/loadMore.js";
export default {
  name: "company-list",
  directives: { permission, loadMore },
  data() {
    return {
      memberData: [],
      pageNum: 1,
      pageSize: 20,
      total: 0,
      queryType: true,
      query: {
        name: "",
        phone: "",
        code:'',
      },
      keyword: {
        name: "",
        phone: "",
        code:'',
      },
      queryPhone: "",
      queryName: "",
      curHeight: null,
      excelData: [],
      companyCategoryId: "",
      companyCategoryName: "",
      deleted: false,
      restoreForm: {
        id: "",
        //   deleted: false,
        companyCategoryId: ""
      },
      payLoads: ""
    };
  },
  components: { Pagination, CategoryPanel, ExportList2Excel },
  created() {
    var _this = this;
    this.loadMember();
    EventBus.$on("company-add", res => {
      // 监听新增完毕
      // 更新列表数组
      _this.memberData.splice(0, 0, _this.formatList(res));
    });
    EventBus.$on("company-edit", res => {
      // 监听新增完毕
      // 更新列表数组
      for (var i = 0; i < _this.memberData.length; i++) {
        if (_this.memberData[i].id == res.id) {
          _this.memberData[i].name = res.name;
          _this.memberData[i].mobile = res.mobile;
          _this.memberData[i].address = res.address;
          _this.memberData[i].companyCategoryName = res.companyCategoryName;
          _this.memberData[i].companyCategoryId = res.companyCategoryId;
        }
      }
    });
  },
  activated() {
    this.payLoads = new Date().getTime();
  },
  mounted() {
    this.comeIn();
    this.beforeMount();
  },
  filters: {
    formatDate: function(value) {
      let date = new Date(value);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      return y + "-" + MM + "-" + d;
    }
  },
  methods: {
    beforeMount() {
      window.onresize = () => {
        return (() => {
          if (this.queryType == false) {
            var h =
              document.documentElement.clientHeight ||
              document.body.clientHeight;
            this.curHeight = h - 266; //减去页面上固定高度height
          } else {
            var h =
              document.documentElement.clientHeight ||
              document.body.clientHeight;
            this.curHeight = h - 220; //减去页面上固定高度height
          }
        })();
      };
    },
    comeIn() {
      console.log("222");
      var h =
        document.documentElement.clientHeight || document.body.clientHeight;
      this.curHeight = h - 220; //减去页面上固定高度height
    },
    //调用数据导出的函数
    handleExport(PageParam) {
      var _this = this;

      //要导出函数携带的参数
      let data = {};
      data.tHeader = [
        "企业名称",
        "手机号码",
        "创建日期",
        "最近修改时间",
        "最近充值时间",
        "最近充值金额",
        "企业分类",
        "地址"
      ];
      data.filterVal = [
        "name",
        "mobile",
        "createDate",
        "modifyDate",
        "rechangeDate",
        "rechangeAmount",
        "companyCategoryName",
        "address"
      ];
      data.filename = "企业列表";

      let params = new URLSearchParams();
      params.append("pageNum", 1);
      params.append("pageSize", 10000);
      params.append("name", _this.keyword.name);
      params.append("companyCategoryId", _this.companyCategoryId);
      params.append("deleted", _this.deleted);
      list(params)
        .then(response => {
          let list = _this.formatList(response.data.data);
          //   console.log("请求的企业信息list------"+JSON.stringify(list) )
          data.list = list;
          _this.$refs.exportList2Excel.handleDownload(data);
          _this.total = response.data.total;
        })
        .catch(error => {
          _this.$refs.exportList2Excel.unlockLoading();
          console.log("error!!");
        });
    },

    //编辑企业信息
    editClick(row) {
      this.$router.push({
        path: "/company/edit",
        query: { id: row.id }
      });
    },

    //过滤成日期
    formatDate2Day(val) {
        if(val){
            let date = new Date(val);
            let y = date.getFullYear();
            let MM = date.getMonth() + 1;
            MM = MM < 10 ? "0" + MM : MM;
            let d = date.getDate();
            d = d < 10 ? "0" + d : d;
            return y + "-" + MM + "-" + d;
        }else{
            return ""
        }

    },

    //过滤到时间
    formatDate2Time(val) {
        if(val){
            let date = new Date(val);
            let y = date.getFullYear();
            let MM = date.getMonth() + 1;
            MM = MM < 10 ? "0" + MM : MM;
            let d = date.getDate();
            d = d < 10 ? "0" + d : d;
            let h = date.getHours();
            h = h < 10 ? "0" + h : h;
            let m = date.getMinutes();
            m = m < 10 ? "0" + m : m;
            let s = date.getSeconds();
            s = s < 10 ? "0" + s : s;
            return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
        }else{
            return ""
        }
    },

    //过滤企业列表
    formatList(data) {
      if (data.length > 0) {
        data.map(item => {
          item.createDate = this.formatDate2Day(item.createDate);
          item.modifyDate = this.formatDate2Time(item.modifyDate);
          item.rechangeDate = this.formatDate2Time(item.rechangeDate);
        });
      }
      return data;
    },

    //请求企业列表
    loadMember(val) {
      // console.log(val)
      var _this = this;
      let params = new URLSearchParams();
      params.append("pageNum", _this.pageNum);
      params.append("pageSize", _this.pageSize);
      params.append('code',_this.keyword.code)
      params.append("name", _this.keyword.name);
      params.append("companyCategoryId", _this.companyCategoryId);
      params.append("deleted", _this.deleted);
      list(params)
        .then(response => {
          let list = response.data.data;
            // console.log("请求的企业信息list------"+JSON.stringify(list) )
          _this.memberData = _this.formatList(list);
          _this.total = response.data.total;
          this.updateScroll();
        })
        .catch(error => {
          console.log("error!!");
        });
    },

    chooseClick() {
      this.queryType = !this.queryType;
      if (this.queryType == false) {
        var h =
          document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 266; //减去页面上固定高度height
      } else {
        var h =
          document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 220; //减去页面上固定高度height
      }
    },
    addClick() {
      this.$router.push({
        path: "/company/add",
        query: {
          companyCategoryId: this.companyCategoryId,
          companyCategoryName: this.companyCategoryName
        }
      });
    },
    deleteMember(data) {
      console.log("data" + JSON.stringify(data));
      var _this = this;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          del(data.id)
            .then(response => {
              // console.log("删除成功后返回的数据--"+JSON.stringify(response))
              _this.memberData.forEach(function(item, index) {
                if (item.id == data.id) {
                  _this.memberData.splice(index, 1);
                }
              });
              _this.$message({
                message: response.content,
                offset: 120,
                center: true
              });
            })
            .catch(error => {
              console.log("error!!");
            });
        })
        .catch(() => {});
    },
    queryClick() {
      this.keyword = this.query;
      this.pageNum = 1;
      this.loadMember();
    },
    resetClick() {
      this.query.phone = "";
      this.query.name = "";
      this.query.code=''
      this.keyword = this.query;
      this.pageNum = 1;
      this.loadMember();
    },

    notClick() {
      this.companyCategoryId = 0;
      this.deleted = false;
      this.loadMember();
    },
    delClick() {
      this.deleted = true;
      this.companyCategoryId = "";
      this.loadMember();
    },
    nodeClick(data) {
      this.deleted = false;
      this.companyCategoryId = data.id;
      this.companyCategoryName = data.queryName;
      this.loadMember();
    },

    //恢复被删除的企业
    restoreMchCourse(row) {
      var _this = this;
      console.log(row);
      this.$confirm("确认恢复?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          _this.restoreForm.id = row.id;
          _this.restoreForm.companyCategoryId = row.companyCategoryId;
          console.log("参数restoreForm" + JSON.stringify(_this.restoreForm));
          restoreCompany(_this.restoreForm)
            .then(response => {
              console.log("企业恢复的请求回来了" + JSON.stringify(response));
              _this.memberData.forEach(function(item, index) {
                if (item.id == row.id) {
                  _this.memberData.splice(index, 1);
                }
              });
              _this.$message({
                message: response.content,
                offset: 120,
                center: true
              });
            })
            .catch(error => {
              console.log("error!!");
            });
        })
        .catch(() => {});
    },

    //跳转到员工列表的页面
    detailClick(row) {
        // console.info("row--"+JSON.stringify(row) )
      this.$router.push({
        path: "/company/employeeList",
        query: { id: row.id, companyName: row.name}
      });
    },
    //重置缓存的滚动距离
    updateScroll() {
      window.sessionStorage.setItem("loadTopcompany-list-table", 0);
      window.sessionStorage.setItem("loadLeftcompany-list-table", 0);
    }
  }
};
</script>

<style scoped>
.el-footerBox {
  height: 50px !important;
  line-height: 50px !important;
  border-top: 1px solid #f2f2f2;
}  .app {
     background-color: rgba(248, 248, 248, 0.8);
   }

/deep/.el-header {
  padding: 10px;
  /* height: 100% !important; */
  padding-bottom: 0;
}

.report_header {
  width: 100%;
  min-height: 40px;
  box-sizing: border-box;
  background-color: rgba(248, 248, 248, 0.8);
  display: flex;
  align-items: center;
  padding-bottom: 5px;
  position: relative;
  padding-left: 5px;
  padding-right: 5px;
}
.report_header_left {
  width: 5px;
  height: 100%;
  background-color: #409EFF;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
}

.report_header_query {
  margin-left: 10px;
  width: 180px;
  margin-top: 5px;
}
</style>
